package com.samphanie.auiu.biz_home.fragment.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import com.samphanie.auiu.common.ui.component.base.BaseViewModel
import com.samphanie.auiu.biz_home.api.homeApiService
import com.samphanie.auiu.library.restful.AuiuCallback
import com.samphanie.auiu.library.restful.AuiuResponse
import com.samphanie.auiu.biz_home.model.HomeModel
import com.samphanie.auiu.biz_home.model.TabCategory

/**
 * @author ZSY
 */
class HomeViewModel(private val savedState: SavedStateHandle) : BaseViewModel() {

    fun queryCategoryTabList(): LiveData<List<TabCategory>?> {
        val liveData = MutableLiveData<List<TabCategory>?>()
        val memCache = savedState.get<List<TabCategory>?>("categoryTabs")
        if (memCache != null) {
            liveData.postValue(memCache)
            return liveData
        }
        homeApiService().queryTabList().enqueue(object : AuiuCallback<List<TabCategory>> {
            override fun onSuccess(response: AuiuResponse<List<TabCategory>>) {
                if (response.successful() && response.data != null) {
                    liveData.postValue(response.data)
                    savedState.set("categoryTabs", response.data)
                } else {
                    liveData.postValue(null)
                }
            }

            override fun onFailed(throwable: Throwable) {
                liveData.postValue(null)
            }
        })
        return liveData
    }

    fun queryTabCategoryList(cateId: String, pageNum: Int, pageSize: Int, cacheStrategy: Int): LiveData<HomeModel?> {
        val liveData = MutableLiveData<HomeModel?>()
        //        val memCache = savedState.get<HomeModel?>("homeModel")
        //        if (memCache != null) {
        //            liveData.postValue(memCache)
        //            return liveData
        //        }
        homeApiService().queryTabCategoryList(cacheStrategy, cateId, pageNum, pageSize)
            .enqueue(object : AuiuCallback<HomeModel> {
                override fun onSuccess(response: AuiuResponse<HomeModel>) {
                    if (response.successful() && response.data != null) {
                        liveData.postValue(response.data)
                        savedState.set("homeModel", response.data)
                    } else {
                        liveData.postValue(null)
                    }
                }

                override fun onFailed(throwable: Throwable) {
                    // finishRefresh(null)
                    liveData.postValue(null)
                }

            })

        return liveData
    }

}